import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import '../../tool/md5_sign.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_yres/model/shop/pdd_list.model.dart';
import 'package:flutter_yres/pages/shop/pdd_detail_page.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_yres/pages/shop/SearchGoods.dart';
class NewPddList extends StatefulWidget {
  String title;
  String id;
  NewPddList({Key key, this.title, this.id}) : super(key: key);

  @override
  _NewPddListState createState() => _NewPddListState();
}

class _NewPddListState extends State<NewPddList> {
  EasyRefreshController _controller = new EasyRefreshController();
  double _listHeight = ScreenUtil.getInstance().setHeight(260); //单个列表高度
  int page = 1;
  var search = '';
  List<PddListModelData> shopData = []; //拼多多商品

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.red,
        title: Text(widget.title),
        actions: <Widget>[
            new IconButton(
                      icon: new Icon(Icons.search, color: Colors.white),
                      iconSize:30.0 ,
                      onPressed: () {
                        Navigator.of(context)
                                .push(new MaterialPageRoute(builder: (context) {
                              return new SearchGoodsPage(type:'2');
                            }));
                      },
            )
          ],
      ),
      body: Container(
        child: new EasyRefresh(
            enableControlFinishRefresh: true,
            enableControlFinishLoad: true,
            controller: _controller,
            header: MaterialHeader(),
            footer: MaterialFooter(),
            child: CustomScrollView(slivers: <Widget>[
              SliverFixedExtentList(
                  delegate: SliverChildBuilderDelegate(_buildListItem,
                      childCount: shopData.length),
                  itemExtent: _listHeight),
            ])),
      ),
      
    );
  }

  Widget _buildListItem(BuildContext context, int index) {
    return new GestureDetector(
        onTap: () {
          //处理点击事件
          PddListModelData model = shopData[index];
          // var gasIds=model.gasid;
          Navigator.push(
              context,
              MaterialPageRoute(
                  //导航打开新视图
                  builder: (context) => PddShopDetailPage(
                      pddmodel: model) //打开第二个页面，并传值，传递值的名称是model
                  ));
        },
        child: Container(
            margin: EdgeInsets.fromLTRB(
                0, ScreenUtil.getInstance().setHeight(15), 0, 0),
            child: Column(
              children: <Widget>[
                Row(children: <Widget>[
                  _leftImage(index),
                  Expanded(
                    child: _rightColumn(index),
                  )
                ], crossAxisAlignment: CrossAxisAlignment.start),
                Divider(
                  height: 1,
                )
              ],
            )));
  }

  Widget _pd(Widget w, {double l, double t, double r, double b}) {
    //边距
    return Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setWidth(l) ?? 0,
            ScreenUtil.getInstance().setHeight(t) ?? 0,
            ScreenUtil.getInstance().setWidth(r) ?? 0,
            ScreenUtil.getInstance().setHeight(b) ?? 0),
        child: w);
  }

  Widget _leftImage(int index) {
    PddListModelData model = shopData[index];
    //左图
    var image = CachedNetworkImage(
      width: ScreenUtil.getInstance().setHeight(180),
      height: ScreenUtil.getInstance().setHeight(180),
      fit: BoxFit.fill,
      imageUrl: model.goods_thumbnail_url,
      placeholder: (context, url) => Image.asset(
        'images/pic_default.png',
        width: ScreenUtil.getInstance().setHeight(180),
        height: ScreenUtil.getInstance().setHeight(180),
        fit: BoxFit.fill,
      ),
      errorWidget: (context, url, error) => Image.asset(
        'images/pic_default.png',
        width: ScreenUtil.getInstance().setHeight(180),
        height: ScreenUtil.getInstance().setHeight(180),
        fit: BoxFit.fill,
      ),
    );
    return _pd(image, l: 20, t: 0, r: 5, b: 40);
  }

  Widget _rightColumn(int index) {
    PddListModelData model = shopData[index];
    //右内容
    var title = Text(
      model.goods_name,
      style: TextStyle(
          color: Colors.black, fontSize: ScreenUtil.getInstance().setSp(26)),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
    var price = RichText(
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(
            text: '¥',
            style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(24))),
        TextSpan(
            text: (model.min_group_price / 100 - model.coupon_discount / 100)
                .toStringAsFixed(2),
            style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(27))),
        TextSpan(
          text: (model.min_normal_price / 100).toStringAsFixed(2),
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(22),
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var volume = Container(
      child: Text('销量' + model.sales_tip,
          style: TextStyle(
              color: Colors.grey,
              fontSize: ScreenUtil.getInstance().setSp(24))),
    );
    var quanHeader = Container(
      width: ScreenUtil.getInstance().setWidth(40),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_header.png"),
          fit: BoxFit.cover,
        ),
      ),
    );
    var quan = Container(
      width: ScreenUtil.getInstance().setWidth(70),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_footer.png"),
          fit: BoxFit.cover,
        ),
      ),
      child: Center(
          child: Text(
        (model.coupon_discount / 100).toString() + '元',
        style: TextStyle(
            color: Colors.white, fontSize: ScreenUtil.getInstance().setSp(24)),
      )),
    );
    var yongjin = Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(20), 0,
          ScreenUtil.getInstance().setWidth(20), 0),
      height: ScreenUtil.getInstance().setWidth(34),
      color: Color.fromRGBO(250, 226, 226, 1),
      child: Center(
          child: Text(
              '预估赚¥' +
                  (((model.min_group_price - model.coupon_discount) *
                              (model.promotion_rate / 1000)) /
                          100)
                      .toStringAsFixed(2),
              style: TextStyle(
                  color: Colors.red,
                  fontSize: ScreenUtil.getInstance().setSp(24)))),
    );
    return new Column(
      children: <Widget>[
        _pd(title, l: 10, t: 0, r: 10, b: 8),
        _pd(volume, l: 10, t: 0, r: 10, b: 8),
        _pd(price, l: 10, t: 0, r: 10, b: 8),
        Container(
          margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
          child: Row(
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Row(
                  children: <Widget>[quanHeader, quan],
                ),
              ),
              Expanded(flex: 2, child: yongjin)
            ],
          ),
        )
        // Row(
        //   children: <Widget>[_pd(price, l: 10, t: 0, r: 10, b: 8), distance],
        // ),
        // _pd(address, l: 10, t: 0, r: 10, b: 8)
      ],
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

  @override
  void initState() {
    getPDDShopList();
    super.initState();
  }

  getPDDShopList() async {
    String url = '';
    Map map = new Map();
    if (widget.title == '实时热销榜' || widget.title == '实时收益榜') {
      map['sort_type'] = widget.title == '实时热销榜' ? '1' : '2';
      url = Api.getTopGoodsList;
      map["page_size"] = "10";
      map["page"] = page;
    } else if (widget.title == '1.9包邮' ||
        widget.title == '今日爆款' ||
        widget.title == '品牌清仓') {
      url = 'http://gw-api.pinduoduo.com/api/router?';
      var timestamp = new DateTime.now().millisecondsSinceEpoch;
      map['type'] = 'pdd.ddk.goods.recommend.get';
      // map["sort_type"] = '';
      map["offset"] = page * 10;
      map["limit"] = "10";
      map["channel_type"] =
          widget.title == '1.9包邮' ? '0' : (widget.title == '今日爆款' ? '1' : '2');
      map['timestamp'] = "$timestamp";
      map["client_id"] = '9cdd5d9fb8ee4d1b94a5f81d005a7922';
      map["data_type"] = "JSON";
      map["version"] = "V1";
      print(map);
      String key = '9a103e4e2cfc3b1ea51df0be47fb6e55e8497169';
      List<String> allKeys = [];
      map.forEach((key, value) {
        if (!(value is MultipartFile)) {
          allKeys.add(key.toString() + value.toString());
        }
      });
      allKeys.sort((obj1, obj2) {
        return obj1.compareTo(obj2);
      });
      String pairsString = allKeys.join("");
      String sign = key + pairsString + key;
      String signString = generateMd5(sign).toUpperCase();
      map['sign'] = signString;
    } else {
      url = Api.getThemeGoodsUrl;
      map['theme_id'] = widget.id.toString();
      print(url);
    }
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response = await HttpUtil().post(url, data: data);
    Map userMap = json.decode(response.data);
    // PddListModelEntity itemEntity = new PddListModelEntity.fromJson(userMap);
    print(userMap);
    if (widget.title == '实时热销榜' || widget.title == '实时收益榜') {
      if (userMap['code'] == 1) {
        if (mounted) {
          setState(() {
            if (page == 1) {
              shopData.clear();
              List<PddListModelData> data = new List<PddListModelData>();
              (userMap["data"]["top_goods_list_get_response"]["list"] as List)
                  .forEach((v) {
                data.add(new PddListModelData.fromJson(v));
              });
              shopData = data;
              _controller.finishRefresh();
            } else {
              List<PddListModelData> data = new List<PddListModelData>();
              (userMap["data"]["top_goods_list_get_response"]["list"] as List)
                  .forEach((v) {
                data.add(new PddListModelData.fromJson(v));
              });
              shopData.addAll(data);
              _controller.finishLoad();
            }
          });
        }
      }
    } else if (widget.title == '1.9包邮' ||
        widget.title == '今日爆款' ||
        widget.title == '品牌清仓') {
      if (userMap.containsKey("goods_basic_detail_response")) {
        if (mounted) {
          setState(() {
            if (page == 1) {
              shopData.clear();
              List<PddListModelData> data = new List<PddListModelData>();
              (userMap["goods_basic_detail_response"]["list"] as List)
                  .forEach((v) {
                data.add(new PddListModelData.fromJson(v));
              });
              shopData = data;
              _controller.finishRefresh();
            } else {
              List<PddListModelData> data = new List<PddListModelData>();
              (userMap["goods_basic_detail_response"]["list"] as List)
                  .forEach((v) {
                data.add(new PddListModelData.fromJson(v));
              });
              shopData.addAll(data);
              _controller.finishLoad();
            }
          });
        }
      }
    } else {
      if (userMap['code'] == 1) {
         if (mounted) {
           setState(() {
             
             if (page == 1) {
              shopData.clear();
              List<PddListModelData> data = new List<PddListModelData>();
              (userMap["data"]["goods_list"] as List)
                  .forEach((v) {
                data.add(new PddListModelData.fromJson(v));
              });
              shopData = data;
              _controller.finishRefresh();
            } else {
              List<PddListModelData> data = new List<PddListModelData>();
              (userMap["data"]["goods_list"] as List)
                  .forEach((v) {
                data.add(new PddListModelData.fromJson(v));
              });
              shopData.addAll(data);
              _controller.finishLoad();
            }
           });
         }
      }
    }
  }
}
